<template>
  <view class="page-container">
    <view class="header-fixed">
      <S1Header title="附加费用配置" :on-back="goBack" />
    </view>

    <view class="content-wrapper">
      <view class="fee-list">
        <view
          v-for="(item, index) in feeList"
          :key="index"
          class="fee-item"
        >
          <view class="fee-form">
            <view class="form-row">
              <text class="form-label">
                项目名称
              </text>
              <input
                v-model="item.name"
                class="form-input"
                placeholder="请输入项目名称"
                @blur="saveFees"
              >
            </view>

            <view class="form-row">
              <text class="form-label">
                税率
              </text>
              <input
                v-model="item.rate"
                class="form-input"
                type="digit"
                placeholder="请输入税率"
                @blur="saveFees"
              >
            </view>

            <view class="form-row">
              <text class="form-label">
                计算方式
              </text>
              <picker
                class="form-picker"
                :value="item.method"
                :range="methodOptions"
                range-key="type"
                @change="onMethodChange($event, item)"
              >
                <view class="picker-text">
                  {{ getMethodLabel(item.method) }}
                </view>
              </picker>
            </view>

            <view class="form-row">
              <text class="form-label">
                支付方
              </text>
              <picker
                class="form-picker"
                :value="item.type"
                :range="payerOptions"
                range-key="label"
                @change="onPayerChange($event, item)"
              >
                <view class="picker-text">
                  {{ getPayerLabel(item.type) }}
                </view>
              </picker>
            </view>

          </view>

          <view class="delete-btn" @click="deleteFee(item.id)">
            <up-icon name="trash" color="#ff4d4f" size="18" />
            <text class="delete-text">
              删除
            </text>
          </view>
        </view>
      </view>
    </view>

    <view v-if="feeList.length < 5" class="add-btn-fixed">
      <button class="add-btn" @click="addFee">
        添加附加费用
      </button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import S1Header from '@/components/S1Header.vue';
import { post } from '@/utils/request';

interface FeeItem {
  id?: number;
  name: string;
  rate: string;
  method: string;
  type: string;
}

defineOptions({ name: 'AdditionalFees' });

const feeList = ref<FeeItem[]>([]);

const methodOptions = [
  { id: '1', type: '计重' },
  { id: '2', type: '计件' },
  { id: '3', type: '直接加' },
  { id: '4', type: '按货款' },
];

const payerOptions = [
  { value: '1', label: '买家出' },
  { value: '2', label: '货主出' },
];

const goBack = () => {
  uni.navigateBack();
};

// 获取附加费用列表
const getFeeList = async () => {
  try {
    const res: any = await post('/syapi/Fujiafei/getFujiafeiData');
    if (res.code === 200) {
      feeList.value = res.data || [];
    }
  }
  catch (error) {
    console.error('获取附加费用失败:', error);
  }
};

// 添加附加费用
const addFee = async () => {
  try {
    const res: any = await post('/syapi/Fujiafei/addFujiafeiData');
    if (res.code === 200) {
      feeList.value = res.data || [];
      uni.showToast({
        title: '添加成功',
        icon: 'success',
      });
    }
    else {
      uni.showToast({
        title: res.msg || '添加失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('添加失败:', error);
    uni.showToast({
      title: '添加失败',
      icon: 'none',
    });
  }
};

// 删除附加费用
const deleteFee = async (id: number) => {
  try {
    const res: any = await post('/syapi/Fujiafei/fujiafeiDelData', { data: { id } });
    if (res.code === 200) {
      feeList.value = res.data || [];
      uni.showToast({
        title: '删除成功',
        icon: 'success',
      });
    }
    else {
      uni.showToast({
        title: res.msg || '删除失败',
        icon: 'none',
      });
    }
  }
  catch (error) {
    console.error('删除失败:', error);
    uni.showToast({
      title: '删除失败',
      icon: 'none',
    });
  }
};

// 保存附加费用
const saveFees = async () => {
  try {
    const res: any = await post('/syapi/Fujiafei/editFujiafeiData', { data: feeList.value });
    if (res.code === 200) {
      feeList.value = res.data || [];
      uni.showToast({
        title: '保存成功',
        icon: 'success',
      });
    }
    else {
      uni.showToast({
        title: res.msg || '保存失败',
        icon: 'none',
      });
      // 恢复数据
      feeList.value = res.data || [];
    }
  }
  catch (error) {
    console.error('保存失败:', error);
    uni.showToast({
      title: '保存失败',
      icon: 'none',
    });
  }
};

// 计算方式变化
const onMethodChange = (e: any, item: FeeItem) => {
  const index = e.detail.value;
  item.method = methodOptions[index].id;
  saveFees();
};

// 支付方变化
const onPayerChange = (e: any, item: FeeItem) => {
  const index = e.detail.value;
  item.type = payerOptions[index].value;
  saveFees();
};

// 获取计算方式标签
const getMethodLabel = (value: string) => {
  const option = methodOptions.find(o => o.id === value);
  return option ? option.type : '请选择';
};

// 获取支付方标签
const getPayerLabel = (value: string) => {
  const option = payerOptions.find(o => o.value === value);
  return option ? option.label : '请选择';
};

onMounted(() => {
  getFeeList();
});
</script>

<style scoped lang="scss">
.page-container {
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header-fixed {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background-color: #fff;
}

.content-wrapper {
  padding: 20rpx 32rpx;
  padding-top: 184rpx;
  padding-bottom: 145rpx;
}

.fee-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.fee-item {
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.fee-form {
  padding: 20rpx 32rpx;
  padding-bottom: 0;
}

.form-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1rpx solid rgba(0, 0, 0, 0.06);

  &:last-child {
    border-bottom: none;
  }
}

.form-label {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
  width: 180rpx;
  flex-shrink: 0;
}

.form-input {
  flex: 1;
  height: 64rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #f8f8f8;
  text-align: right;
}

.form-picker {
  flex: 1;
}

.picker-text {
  height: 64rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  border: 1rpx solid #e5e5e5;
  border-radius: 8rpx;
  background-color: #f8f8f8;
  line-height: 64rpx;
  text-align: right;
  color: #333;
}

.delete-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  height: 88rpx;
  padding: 0 32rpx;
}

.delete-text {
  font-size: 28rpx;
  color: #ff4d4f;
}

.add-btn-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 32rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 100;
}

.add-btn {
  width: 100%;
  height: 88rpx;
  font-size: 30rpx;
  color: #fff;
  background-color: #4ca75b;
  border: none;
  border-radius: 12rpx;
  line-height: 88rpx;
}
</style>
